package com.hn.springcloud.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.ArrayList;
import java.util.List;

/**
 * hanni
 * 2019/2/14 0014
 * 8:12
 *
 * 2.	自定义负载均衡算法：让每一个服务器被访问3次后换成下一个服务器，轮询。
 */

public class MyBalanceRule extends AbstractLoadBalancerRule {
    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        
    }

    @Override
    public Server choose(Object o) {

        //负载均衡的入口
        ILoadBalancer loadBalancer = getLoadBalancer();

        //获取所有可以访问的服务器
        //List<Server> reachableServers = loadBalancer.getReachableServers();

        //获取所有的服务器
        List<Server> allServers = loadBalancer.getAllServers();

        int count = 0;
        count ++;
        if (count<3){
            return allServers.get(0);

        }else{
            count = 0;
            return allServers.get(1);
        }

        /*List<Server>  servers = new ArrayList<>();
        servers.add(new Server("provider1",8001));
        servers.add(new Server("provider2",8005));

        loadBalancer.addServers(servers);*/
    }
}
